package cn.zn.wx.resolver;

import cn.zn.framework.common.utils.Constant;
import cn.zn.framework.redis.RedisUtils;
import cn.zn.modules.zzsys.inter.annotation.LoginUser;
import cn.zn.modules.zzsys.inter.dto.LoginUserDTO;
import cn.zn.wx.interceptor.AuthorizationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 *
 * @author zn
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(LoginUserDTO.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户凭证
        Object token = request.getAttribute(AuthorizationInterceptor.TOKEN, 0);
        if (token == null) {
            return null;
        }

        //获取用户信息
        LoginUserDTO loginUser = redisUtils.hget(Constant.REDIS_LOGIN_USER, token.toString(), LoginUserDTO.class);

        return loginUser;
    }
}
